package com.ddiviewer;

import android.util.*;
import android.view.View;

import java.io.*;

import org.apache.http.client.methods.*;
import org.apache.http.client.*;
import org.apache.http.*;
import org.apache.http.impl.client.*;
import org.apache.http.util.EntityUtils;


/*
 * Connection information. 
 */
public class Connection {	
	public Connection() {}
	
	/*
	 * connect method
	 * INPUTS:
	 * 		url => URL of website
	 * 		tab,keyword,nameonly => GET variables
	 * 		v => android view reference, for writing output
	 */
    public String connect (String url, String tab, String keyword, String nameonly, View v) 
    												throws ClientProtocolException, IOException, Exception {

    	StringBuilder		urlBuilder 	= new StringBuilder();
    	urlBuilder.append(url + 
    			          "?Keywords=" + java.net.URLEncoder.encode(keyword) + 
    			          "&Tab=" + java.net.URLEncoder.encode(tab) + 
    			          "&NameOnly=" + java.net.URLEncoder.encode(nameonly)
    			         );
    	
    	try {
    		HttpGet request = new HttpGet(urlBuilder.toString());
    		Log.i("REQUEST_URL", urlBuilder.toString());
    		HttpClient client = new DefaultHttpClient();
    		HttpResponse response = client.execute(request);
    		
    		int status = response.getStatusLine().getStatusCode();
    		
    		// we assume that the response body contains the error message
    		if (status != HttpStatus.SC_OK) {
    			Log.e("HTTP CLIENT", EntityUtils.toString(response.getEntity()));
    		} else {
    			return EntityUtils.toString(response.getEntity());
    		}
    	} catch (Exception e) {
    		Log.e("EXCEPTION", e.getMessage());
    	}

    	return null;
    }

}
